package com.simon.app.october.modules.job.utils;

import com.google.gson.Gson;
import com.simon.app.october.common.utils.SpringContextUtils;
import com.simon.app.october.modules.job.entity.ScheduleJobEntity;
import com.simon.app.october.modules.job.entity.ScheduleJobLogEntity;
import com.simon.app.october.modules.job.service.ScheduleJobLogService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ScheduleJob extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String jsonJob = context.getMergedJobDataMap().getString(ScheduleJobEntity.JOB_PARAM_KEY);
        ScheduleJobEntity jobEntity = new Gson().fromJson(jsonJob, ScheduleJobEntity.class);

        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");

        // 保存执行记录
        ScheduleJobLogEntity logEntity = new ScheduleJobLogEntity();
        logEntity.setJobId(jobEntity.getJobId());
        logEntity.setBeanName(jobEntity.getBeanName());
        logEntity.setMethodName(jobEntity.getMethodName());
        logEntity.setParams(jobEntity.getParams());
        logEntity.setCreateTime(new Date());

        // 开始执行的时间戳
        long starTime = System.currentTimeMillis();

        try {

            logger.info("任务id："+ jobEntity.getJobId()+"开始执行");

            ScheduleRunnable task = new ScheduleRunnable(jobEntity.getBeanName(), jobEntity.getMethodName(), jobEntity.getParams());

            Future<?> future = service.submit(task);
            future.get();

            logEntity.setStatus(0);
            logger.info("任务id："+ jobEntity.getJobId()+"执行完毕");

        } catch (Exception e) {
            logger.info("任务id："+ "执行失败");
            logEntity.setStatus(1);
            logEntity.setError(e.toString());
        } finally {
            // 任务执行时长
            long times = System.currentTimeMillis() - starTime;
            logEntity.setTimes(times);
            scheduleJobLogService.save(logEntity);
        }

    }
}
